package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egoo.ticket.server.dao.*;
import com.egoo.ticket.server.pojo.dto.SystemMsgDto;
import com.egoo.ticket.server.pojo.entity.*;
import com.egoo.ticket.server.project.ProjectConstant;
import com.egoo.ticket.server.project.sunong.SuNongBaseUtil;
import com.egoo.ticket.server.service.EripDataSynService;
import com.egoo.ticket.server.service.MqBusinessExecuteService;
import com.egoo.ticket.server.service.TriggerExecuteService;
import com.egoo.ticket.server.utils.common.ConstantCode;
import com.egoo.ticket.server.utils.common.MsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MqBusinessExecuteServiceImpl implements MqBusinessExecuteService {
    @Autowired
    WorkOrderDao workOrderDao;
    @Autowired
    EripDataSynService eripDataSynService;
    @Autowired
    EwsUserDao ewsUserDao;
    @Autowired
    private TriggerExecuteService triggerExecuteService;
    @Value("${server.project-sign}")
	private String projectSign;
    @Autowired
	private SuNongBaseUtil suNongBaseUtil;
    @Autowired
	private MsgNotifySettingMapper msgNotifySettingMapper;
    @Autowired
	private MsgSettingRelationMapper msgSettingRelationMapper;
    @Autowired
	private MsgTemplateMapper msgTemplateMapper;
    @Autowired
	private MsgUtil msgUtil;


    @Override
    public void mqExecuteTrigger(String msgContent) {
		// 设置触发器时间类条件过期时间
		triggerExecuteService.setWorkOrderTimeConditionTrigger(msgContent);
		// 工单触发器执行
		triggerExecuteService.triggerExecuteByWorkOrderId(msgContent);

    }

    /**
     * @Author: Donny_dong
     * @Description: mq发送系统消息
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    @Override
    public void mqExecuteSysMsg(String workOrderId, String msgSign) {
        WorkOrder workOrder = workOrderDao.selectById(workOrderId);
        if (Objects.isNull(workOrder)){
            log.info("对应的工单不存在");
            return;
        }
        SystemMsgDto systemMsgDto = getSystemMsgDto(workOrder, msgSign);
        if (Objects.isNull(systemMsgDto)){
            log.info("获取该系统消息参数为空,不能发送");
            return;
        }
        eripDataSynService.sendSystemMsg(systemMsgDto);

    }
    /**
     * @Author: Donny_dong
     * @Description: 获取系统消息参数
     * @Param: 
     * @return: 
     * @Date: 2020/8/31
     */
    private SystemMsgDto getSystemMsgDto(WorkOrder workOrder, String msgSign) {
        if (ConstantCode.SysDictCode.PUSH_MSG_HANDLER.equals(msgSign)){
            return getCurrentHandlerParamForSysMsg(workOrder,msgSign);
        }
        return null;
    }
    /**
     * @Author: Donny_dong
     * @Description: 获取当前处理人的系统消息参数
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    private SystemMsgDto getCurrentHandlerParamForSysMsg(WorkOrder workOrder,String msgSign) {
        try {
            String currentHandlerId = workOrder.getCurrentHandlerId();
            if (StringUtils.isEmpty(currentHandlerId)){
                log.info("该工单当前处理人为空");
                return null;
            }
            List<String> currentHandlerList = Arrays.asList(currentHandlerId.split(","));
            String sysTitle = "当前处理的消息标题";
            String sysContent = "当前处理人的处理内容";
            SystemMsgDto<List> systemMsgDto = new SystemMsgDto<>();
            systemMsgDto.setTitle(sysTitle);
            systemMsgDto.setContent(sysContent);
            systemMsgDto.setTargets(currentHandlerList);
            systemMsgDto.setSenderId(ConstantCode.SystemMsgConfig.SENDER_ID_SYS);
            systemMsgDto.setTenantId(workOrder.getTenantId());
            return systemMsgDto;
        } catch (Exception e) {
            log.error("处理当前处理人的系统消息参数异常"+e);
            return null;
        }
    }
    
    
    /**
     * @Author: Donny_dong
     * @Description: mq发送短信
     * @Param: 
     * @return: 
     * @Date: 2020/8/31
     */
    @Override
    public void mqExecuteMsg(String workOrderId, String msgSign,String msgType) {
        WorkOrder workOrder = workOrderDao.selectById(workOrderId);
        if (Objects.isNull(workOrder)){
            log.info("对应的工单不存在");
            return;
        }
        //由于短信发送不支持数组，不将参数返回，直接发送；
        getMsgBody(workOrder,msgSign,msgType);
    }

    /**
     * @Author: Donny_dong
     * @Description: 获取发送短信参数
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    private JSONObject getMsgBody(WorkOrder workOrder, String msgSign,String msgType) {
        if (ConstantCode.SysDictCode.SEND_MSG_CURRENT_HANDLER.equals(msgSign)){
            getCurrentHandlerParamForMsg(workOrder,msgSign,msgType);
        }
        return null;
    }

    /**
     * @Author: Donny_dong
     * @Description: 获取当前处理人的发送短信参数
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    private void getCurrentHandlerParamForMsg(WorkOrder workOrder,String msgSign,String msgType) {
        String msgTemplate = getTemplate(workOrder, msgSign,msgType);
        if (StringUtils.isEmpty(msgTemplate)){
            log.info("短信模板为空，不能发送短信");
            return;
        }
        String currentHandlerIds = workOrder.getCurrentHandlerId();
        if (StringUtils.isEmpty(currentHandlerIds)){
            log.info("当前处理人信息为空，无法发送短信");
            return;
        }
        List<String> currentHandlerList= Arrays.asList(currentHandlerIds.split(","));
        List<EwsUser> userList = getUserList(currentHandlerList, workOrder);
        if (CollectionUtils.isEmpty(userList)){
            log.info("对应的用户不存在，无法送短信");
            return;
        }
        for (EwsUser ewsUser:userList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("phoneNumber",ewsUser.getPhone());
            jsonObject.put("content",msgTemplate);
            jsonObject.put("tenantId",workOrder.getTenantId());
            jsonObject.put("userId",ConstantCode.SYSTEM_OPERATION_LOGO);
            jsonObject.put("msgTypeName","短信");
            jsonObject.put("workOrderId",workOrder.getId());
            eripDataSynService.sendMsg(jsonObject);
        }

    }

    /**
     * @Author: Donny_dong
     * @Description: 获取用户信息
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    private List<EwsUser> getUserList(List<String> currentHandlerList, WorkOrder workOrder) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("userIds",currentHandlerList);
        paramMap.put("tenantId",workOrder.getTenantId());
        List<EwsUser> ewsUsers = ewsUserDao.selectAllUserList(paramMap);
        return ewsUsers;
    }

    /**
     * @Author: Donny_dong
     * @Description: 获取短信模板
     * @Param:
     * @return:
     * @Date: 2020/8/31
     */
    private String getTemplate(WorkOrder workOrder, String msgSign,String msgType) {
        JSONArray template = eripDataSynService.getTemplate();
        //根据项目需求调整对应模板
        String msgTemplate= null;
        if (CollectionUtils.isEmpty(template)){
             log.info("短信模板为空");
             return msgTemplate;
        }
        if(ProjectConstant.ProjectSign.SUNONG.equals(projectSign)) {
			msgTemplate = suNongBaseUtil.getMsgTemplate(template,msgType);
        }
        return msgTemplate;
    }

	@Override
	public void mqExecuteGeneralMsg(String msgContent,String msgNotifyType) {
		WorkOrder workOrder = workOrderDao.selectById(msgContent);
		Long workOrderTypeId = workOrder.getWorkOrderTypeId();
		QueryWrapper<MsgNotifySetting> notifySettingQueryWrapper = new QueryWrapper<>();
		notifySettingQueryWrapper.lambda().eq(MsgNotifySetting::getWorkOrderTypeId,workOrderTypeId)
											.eq(MsgNotifySetting::getNotifyType,msgNotifyType)
											.eq(MsgNotifySetting::getStatus,1)
											.eq(MsgNotifySetting::getTenantId,workOrder.getTenantId());
		List<MsgNotifySetting> msgNotifySettings = msgNotifySettingMapper.selectList(notifySettingQueryWrapper);
		if (CollectionUtils.isEmpty(msgNotifySettings)){
			log.info("此消息通知设置不存在:"+msgNotifySettings);
			return;
		}

		for (MsgNotifySetting msgNotifySetting:msgNotifySettings) {
			String notifyType = msgNotifySetting.getNotifyType();
			QueryWrapper<MsgSettingRelation> relationQueryWrapper = new QueryWrapper<>();
			relationQueryWrapper.lambda().eq(MsgSettingRelation::getMsgNotifyId,msgNotifySetting.getId());
			List<MsgSettingRelation> msgSettingRelations = msgSettingRelationMapper.selectList(relationQueryWrapper);
			if (CollectionUtils.isEmpty(msgSettingRelations)){
				log.info("此消息通知未设置发送信息:"+msgSettingRelations);
				continue;
			}
			msgUtil.getMsgCondition(notifyType,msgSettingRelations,workOrder);
		}



	}




}
